<?php

namespace app\site\controller\store;

use app\common\exception\MiException;
use app\common\service\CommonSiteConfigService;
use app\common\service\CommonStoreManagerService;
use app\common\validate\StoreManagerValidate;
use app\model\site\User;
use app\model\store\StoreManager;
use app\model\store\StoreManagerBalanceLog;
use app\site\controller\AController;
use app\site\service\SiteAuthService;
use app\site\service\store\StoreManagerService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

class StoreManagerController extends AController
{
    private StoreManagerService $service;
    private int $siteId;

    /**
     * @throws MiException
     */
    protected function initialize()
    {
        $this->service = StoreManagerService::instance();
        $this->siteId = SiteAuthService::instance()->getSiteId();
    }

    /**
     * @throws DbException|MiException
     */
    public function index(){
        $where = [];
        $key = $this->param('where.key');
        if ($key) $where[] = ['id|nickname|mobile', 'like', '%'.$key.'%'];
        return $this->reqSer->setService(StoreManagerService::instance()->setWhere($where))->setPaginate()->getResponse();
    }

    /**
     * 获取不分页的列表
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function select(){
        $ids = $this->param('user_ids', '');
        $limit = $this->param('limit', 0);
        $where = [];
        if ($ids) $where[] = ['id', 'in', $ids];

        $ser = StoreManagerService::instance()
            ->setLimit($limit)
            ->setWhere($where);
        return $this->reqSer->setService($ser)->setSelect()->getResponse();
    }

    /**
     *  创建店长
     */
    public function add(): Json
    {
        $post = $this->post();
        $post['site_id'] = $this->siteId;
        // 验证数据
        validate(StoreManagerValidate::class)->scene('add')->check($post);
        StoreManagerService::instance()->create($post);
        return jsonSuccess();
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function edit(){
        if(request()->isPost()){
            $post = $this->post();
            // 验证数据
            validate(StoreManagerValidate::class)->scene('edit')->check($post);
            StoreManagerService::instance()->update($post, ['id' => $post['id']]);
            return jsonSuccess();
        }else{
            return $this->reqSer->setService(StoreManagerService::instance())->setFind()->getResponse();
        }
    }

    /**
     * 店长审核
     * @return Json
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException|MiException
     */
    public function audit(): Json
    {
        $post = $this->post();
        $post['audit_status'] = ($post['audit_status']??0) ? 1:-1;
        $manager = StoreManager::find($post['id']);
        $user = User::with(['parent.storeManager'])->find($manager->user_id);  // 店长所属会员
        $siteId = SiteAuthService::instance()->getSiteId();
        $distConfig = CommonSiteConfigService::instance()->getConfigValue($siteId, CommonSiteConfigService::DIST);

        // 如果是审核通过，进行绑定上级，发放样品基金等操作
        if ($post['audit_status'] == 1){
            // 发放样品基金
            $balance = 298;
            $post['balance'] = $balance;
            // 创建当前店长的样品基金记录
            StoreManagerBalanceLog::create([
                'site_id' => $siteId,
                'user_id' => $manager->user_id,
                'rel_id' => 0,
                'rel_model' => '',
                'reward_type' => 1,
                'note' => '成为店长',
                'amount' => $balance,
                'rate' => 0,
                'price' => 0,
            ]);

            // 存在上级 && 上级是店长 && 上级的店长没有被禁用
            if ($user->parent && $user->parent->storeManager && $user->parent->storeManager->status == 1){
                // 绑定店长的上下级关系
                $post['parent_id'] = $user->parent->storeManager->id;
                // 每邀请够5个店长，给上级发放200样品基金
                $parentManager = $user->parent->storeManager;
                // 邀请店长数量+1
                $invite = $parentManager->store_manager_num+1;
                if (($parentManager->store_manager_num+1) == $distConfig['store_manager_num']){
                    // 将邀请店长数量重置为0
                    $invite = 0;
                    // 发放样品基金金额
                    $jijin = $distConfig['store_manager_num_price'];
                    // 发放样品基金
                    $parentManager->balance += $jijin;
                    // 创建样品基金明细
                    StoreManagerBalanceLog::create([
                        'site_id' => $siteId,
                        'user_id' => $parentManager->user_id,
                        'rel_id' => 0,
                        'rel_model' => '',
                        'reward_type' => 2,
                        'note' => '邀请店长',
                        'amount' => $jijin,
                        'rate' => 0,
                        'price' => 0,
                    ]);

                }
                // 修改最新的邀请店长数量
                $parentManager->store_manager_num = $invite;
                // 保存信息
                $parentManager->save();
            }
        }

        StoreManager::update($post);
        return jsonSuccess();
    }

    /**
     * 店长样品基金明细列表
     * @return Json
     * @throws DbException
     */
    public function balanceLogPaginate(): Json
    {
        $uid = $this->param('where.user_id');
        $where = [
            ['site_id', '=', $this->siteId]
        ];
        if ($uid) $where[] = ['user_id', '=', $uid];
        $query = StoreManagerBalanceLog::where($where);
        return $this->jsonPaginate($query);
    }

    /**
     * 释放冻结中的佣金
     * @throws DbException
     */
    public function freeDistReward(): Json
    {
        $month = $this->param('month');
        $dateStr = date('Y-m', strtotime($month));
        CommonStoreManagerService::instance()->freeStoreManagerPrice($dateStr);
        return jsonSuccess();
    }
}
